import React, { useMemo, useState, useRef } from "react";
import styles from "./index.module.less";
import { getTableColumns, getSearchColumns } from "./constant";
import { Modal, message, Button, Dropdown, Menu } from "antd";
import SuperTable from "@/components/SuperTable";
import cs from "classnames";
import {
	getTaskList,
	startTaskApi,
	cancelTaskApi,
	distributeTaskApi,
	stopTaskApi,
	updateTaskOrder,
	copyTaskApi,
	deleteTaskApi
} from "@/api/modules/task";
import useUrl from "@/hooks/useUrl";
import SearchBox from "@/components/SearchBox";
import { PlusOutlined, EllipsisOutlined } from "@ant-design/icons";
import { getTaskLevelDict, getDictByCode } from "@/api/modules/dict";
import { useRequest } from "ahooks";
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import { cloneDeep, omit } from "lodash";

const type = "DraggableBodyRow";

interface DraggableBodyRowProps {
	index: number;
	moveRow: (dragIndex: number, hoverIndex: number) => void;
	onDragEnd?: () => void;
	className?: string;
	style?: React.CSSProperties;
	[key: string]: any;
}

const DraggableBodyRow: React.FC<DraggableBodyRowProps> = ({ index, moveRow, onDragEnd, className, style, ...restProps }) => {
	const ref = React.useRef<HTMLTableRowElement>(null);

	const [{ isOver, dropClassName }, drop] = useDrop({
		accept: type,
		collect: monitor => {
			const { index: dragIndex } = monitor.getItem() || {};
			if (dragIndex === index) {
				return {};
			}
			return {
				isOver: monitor.isOver(),
				dropClassName: dragIndex < index ? " drop-over-downward" : " drop-over-upward"
			};
		},
		drop: (item: any) => {
			if (item.index !== index) {
				moveRow(item.index, index);
				// 延迟调用保存函数，确保状态更新完成
				setTimeout(() => {
					onDragEnd && onDragEnd();
				}, 100);
			}
		}
	});

	const [{ isDragging }, drag] = useDrag({
		type,
		item: { index },
		collect: monitor => ({
			isDragging: monitor.isDragging()
		})
	});

	drop(drag(ref));

	return (
		<tr
			ref={ref}
			className={`${className}${isOver ? dropClassName : ""}${isDragging ? " dragging" : ""}`}
			style={{
				cursor: "move",
				opacity: isDragging ? 0.5 : 1,
				...style
			}}
			{...restProps}
		/>
	);
};

export default () => {
	const dataTableRef = useRef<any>();
	const { data: data1 } = useRequest(() => getTaskLevelDict({ parentId: 0, code: "JOB_STATUS" }));
	const { data: data2 } = useRequest(() => getDictByCode({ parentId: 0, code: "JOB_TYPE" }));
	const { data: data3 } = useRequest(() => getDictByCode({ parentId: 0, code: "JOB_ROUTE" }));
	const { data: data4 } = useRequest(() => getDictByCode({ parentId: 0, code: "JOB_VEHICLE" }));
	const taskStatusList = data1?.data;
	const taskTypeList = data2?.data;
	const taskRouteList = data3?.data;
	const vehType = data4?.data;
	const { navigate } = useUrl();
	const [params, setParams] = useState({});
	const [pageData, setPageData] = useState<{ pageSize?: number; pageNum?: number }>({});
	const [data, setData] = useState<any[]>([]);

	const handleRequest = async (params: any) => {
		const paramsCopy = cloneDeep(params);
		const newParams = omit(paramsCopy, ["pageSize", "current"]);
		const requestData: any = {
			page: {
				pageSize: params.pageSize,
				pageNum: params.current
			},
			...newParams
		};
		setPageData({
			pageSize: params.pageSize,
			pageNum: params.current
		});
		const res = await getTaskList(requestData);
		const newData = res?.data?.list ?? [];
		setData(newData);
		return {
			total: res?.data?.total ?? 0,
			data: newData
		};
	};

	const newColumns = [
		...getTableColumns({ taskStatusList, taskTypeList, taskRouteList, vehType }),
		{
			title: "操作",
			width: 160,
			fixed: "right",
			dataIndex: "action-render",
			render: (text: string, record: any) => {
				const handleView = () => {
					navigate(`/task/list/detail?detailId=${record.id}`, { state: record });
				};

				const handleEdit = () => {
					navigate(`/task/list/add?detailId=${record.id}`, { state: record });
				};

				const handleStartTask = () => {
					Modal.confirm({
						icon: null,
						title: "开始任务提示？",
						content: `确认开始${record?.jobName}吗？`,
						closable: true,
						onOk: c => {
							startTaskApi({ id: record?.id }).then((res: any) => {
								if (res?.code === RESULT_CODES.SUCCESS) {
									message.success("任务开始成功");
									c?.();
									dataTableRef?.current?.reload();
								}
							});
						}
					});
				};

				const handleCancelTask = () => {
					Modal.confirm({
						icon: null,
						title: "取消任务提示？",
						content: `确认取消${record?.jobName}吗？`,
						closable: true,
						onOk: c => {
							cancelTaskApi({ id: record?.id }).then((res: any) => {
								if (res?.code === RESULT_CODES.SUCCESS) {
									message.success("任务取消成功");
									c?.();
									dataTableRef?.current?.reload();
								}
							});
						}
					});
				};

				const handleDistribute = () => {
					Modal.confirm({
						icon: null,
						title: "确认下发站点提示？",
						content: `确认下发${record?.jobName}吗？`,
						closable: true,
						onOk: c => {
							distributeTaskApi({ id: record?.id }).then((res: any) => {
								if (res?.code === RESULT_CODES.SUCCESS) {
									message.success("下发成功");
									c?.();
									dataTableRef?.current?.reload();
								}
							});
						}
					});
				};

				const handleStopTask = () => {
					Modal.confirm({
						icon: null,
						title: "中止任务提示",
						content: `确认中止${record?.jobName}吗？`,
						closable: true,
						onOk: c => {
							stopTaskApi({ id: record?.id }).then((res: any) => {
								if (res?.code === RESULT_CODES.SUCCESS) {
									message.success("任务中止成功");
									c?.();
									dataTableRef?.current?.reload();
								}
							});
						}
					});
				};

				const handleCopyTask = () => {
					Modal.confirm({
						icon: null,
						title: "复制任务提示",
						content: `确认复制${record?.jobName}吗？`,
						closable: true,
						onOk: c => {
							copyTaskApi({ id: record?.id }).then((res: any) => {
								if (res?.code === RESULT_CODES.SUCCESS) {
									message.success("任务复制成功");
									c?.();
									dataTableRef?.current?.reload();
								}
							});
						}
					});
				};

				const handleDeleteTask = () => {
					Modal.confirm({
						icon: null,
						title: "删除任务提示",
						content: `确认删除${record?.jobName}吗？`,
						closable: true,
						onOk: c => {
							deleteTaskApi({ id: record?.id }).then((res: any) => {
								if (res?.code === RESULT_CODES.SUCCESS) {
									message.success("任务删除成功");
									c?.();
									dataTableRef?.current?.reload();
								}
							});
						}
					});
				};

				// 根据任务状态决定显示哪些按钮
				const getActionButtons = () => {
					if (record.jobStatus === 0) {
						return [
							<div key="view" className={styles.tableBtn} onClick={handleView}>
								查看
							</div>,
							<div key="edit" className={styles.tableBtn} onClick={handleStartTask}>
								开始
							</div>,
							<Dropdown
								key="more"
								overlay={
									<Menu>
										<Menu.Item key="start" onClick={handleEdit}>
											编辑
										</Menu.Item>
										<Menu.Item key="copy" onClick={handleCopyTask}>
											复制
										</Menu.Item>
										<Menu.Item key="cancel" onClick={handleCancelTask}>
											取消
										</Menu.Item>
										<Menu.Item key="delete" onClick={handleDeleteTask}>
											删除
										</Menu.Item>
									</Menu>
								}
							>
								<a>
									<EllipsisOutlined style={{ color: "#01b2a8", fontSize: "16px" }} />
								</a>
							</Dropdown>
						];
					} else if (record.jobStatus === 1) {
						return [
							<div key="view" className={styles.tableBtn} onClick={handleView}>
								查看
							</div>,
							<div key="distribute" className={styles.tableBtn} onClick={handleDistribute}>
								下发
							</div>,
							<Dropdown
								key="more"
								overlay={
									<Menu>
										<Menu.Item key="stop" onClick={handleStopTask}>
											中止
										</Menu.Item>
										<Menu.Item key="copy" onClick={handleCopyTask}>
											复制
										</Menu.Item>
										<Menu.Item key="cancel" onClick={handleCancelTask}>
											取消
										</Menu.Item>
									</Menu>
								}
							>
								<a>
									<EllipsisOutlined style={{ color: "#01b2a8", fontSize: "16px" }} />
								</a>
							</Dropdown>
						];
					} else {
						return [
							<div key="view" className={styles.tableBtn} onClick={handleView}>
								查看
							</div>,
							<div key="copy" className={styles.tableBtn} onClick={handleCopyTask}>
								复制
							</div>,
							<div key="copy" className={cs(styles.tableBtn, styles.lastOne)} onClick={handleDeleteTask}>
								删除
							</div>
						];
					}
				};

				return getActionButtons();
			}
		}
	];

	const NEW_SEARCH_COLUMNS = useMemo(() => {
		return getSearchColumns({ taskStatusList, taskTypeList });
	}, [taskStatusList, taskTypeList]);

	const handleAdd = () => {
		navigate(`/task/list/add`);
	};

	const handleSearch = (e: any) => {
		setParams(e);
	};

	const moveRow = (dragIndex: number, hoverIndex: number) => {
		const dragRow = data[dragIndex];
		setData(prevData => {
			const newData = [...prevData];
			newData.splice(dragIndex, 1);
			newData.splice(hoverIndex, 0, dragRow);
			return newData;
		});
	};

	// 保存拖拽后的新顺序
	const saveNewOrder = async () => {
		try {
			const orderData = data.map((item: any, index: number) => ({
				id: item.id,
				order: ((pageData?.pageNum - 1) * pageData?.pageSize + index) + 1
			}));

			const res: any = await updateTaskOrder({ taskOrders: orderData });
			if (res?.code === RESULT_CODES.SUCCESS) {
				message.success("任务排序更新成功");
			} else {
				message.error("任务排序更新失败");
				// 如果保存失败，重新加载数据
				dataTableRef?.current?.reload();
			}
		} catch (error) {
			message.error("任务排序更新失败");
			// 如果保存失败，重新加载数据
			dataTableRef?.current?.reload();
		}
	};

	return (
		<div className={styles.flexContainer}>
			<div className={styles.rightModule}>
				<SearchBox columns={NEW_SEARCH_COLUMNS} onSearch={handleSearch}>
					<div></div>
				</SearchBox>
				<div
					className={cs({
						[styles.container]: true
					})}
				>
					<div className={styles.operation_group}>
						<Button icon={<PlusOutlined />} type="primary" onClick={handleAdd}>
							新增
						</Button>
						{/* <Button icon={<DeleteOutlined />} type="default">删除</Button> */}
					</div>
					<DndProvider backend={HTML5Backend}>
						<SuperTable
							params={{
								...params
							}}
							ref={dataTableRef}
							rowKey="id"
							columns={newColumns}
							request={handleRequest}
							scroll={{ x: "900" }}
							dataSource={data}
							components={{
								body: {
									row: (props: any) => {
										const index = data.findIndex((item: any) => item.id === props["data-row-key"]);
										return <DraggableBodyRow index={index} moveRow={moveRow} onDragEnd={saveNewOrder} {...props} />;
									}
								}
							}}
						/>
					</DndProvider>
				</div>
			</div>

		</div>
	);
};
